import { useEffect, useRef } from "react"
import SyntaxHighlighter from '@/components/SyntaxHighlighter'

const code1 = `
  const setImg = () => {
    const imgs = containerRef.current.querySelectorAll('img')
    imgs.forEach((img) => {
      const height = img.getBoundingClientRect().height
      const rows = Math.ceil(height / 10)
      img.style.gridRowStart = 'span ' + rows
    })
  }

  .second-container {
    display: grid;
    grid-template-columns: repeat(3, 1fr);
    gap: 8px;
    grid-auto-rows: 2px;
    img {
      width: 100%;
    }
  }
`

const code2 = `
  const setImg = () => {
    const imgs = containerRef.current.querySelectorAll('img')
    imgs.forEach((img) => {
      const width = img.getBoundingClientRect().width
      const columns = Math.ceil(width / 10)
      img.style.gridColumnStart = 'span ' + columns
    })
  }

  .second-container {
    display: grid;
    grid-template-rows: repeat(3, 1fr);
    gap: 8px;
    grid-auto-columns: 2px;
    grid-auto-flow: column;
    height: 100vh;
    img {
      height: 100%;
    }
  }
`

function SecondView({ listData }) {
  const containerRef = useRef()

  const setImg = () => {
    const imgs = containerRef.current.querySelectorAll('img')
    imgs.forEach((img) => {
      const height = img.getBoundingClientRect().height
      const rows = Math.ceil(height / 10)
      img.style.gridRowStart = `span ${rows}`
    })
  }

  useEffect(() => {
    setImg()
  }, [])

  return (
    <>
      <h3>grid 布局</h3>
      <p>实现方式：利用 grid 布局将容器切割成足够小的网格，各元素的高度均为该网格的倍数，计算各元素的高度并给该元素分配对应的网格即可</p>
      <p>方案特点：自由度很高，不仅能实现竖向的瀑布流，还能实现横向的瀑布流，只需要按照宽高计算占据的网格，便能在 grid 布局中填充</p>
      <p>实际应用：能够适用于大多数的场景，但若元素较多时逐一计算并设置元素样式可能造成卡顿</p>

      <h5>竖向</h5>
      <SyntaxHighlighter children={code1} />

      <h5>横向</h5>
      <SyntaxHighlighter children={code2} />

      <h5>竖向示例：</h5>
      <div ref={containerRef} className="second-container">
        { listData.map((item) => 
          <img key={item} src={item} />
        ) }
      </div>
    </>
  )
}

export default SecondView